#!/usr/bin/python3
import gc
import os
from openpyxl import load_workbook
import json
from .Base_Plugin import Base_Plugin


class Permission:
    def __init__(
        self,
        code: str,
        parent_code: str,
        name_cn: str,
        name_en: str,
        _type: str,
        _path: str,
        remarks: str,
        default_flag: bool,
    ) -> None:
        self.SPACE = " "
        self.code = code
        self.parent_code = parent_code if parent_code is not None else ""
        self.name = json.dumps(
            obj={"cn": name_cn, "en": name_en if name_en is not None else name_cn},
            ensure_ascii=False,
            separators=(",", ":"),
        )
        self._type = _type
        self._path = _path if _path is not None else ""
        self.remarks = remarks if remarks is not None else ""
        self.default_flag = default_flag if default_flag is not None else ""

    def sql(self, tenant):
        if tenant is None:
            table_name = "hr_permission"
        else:
            table_name = "{}{}hr_permission{}{}".format(
                tenant["table_prefix"],
                tenant["delimiter"],
                tenant["delimiter"],
                tenant["tenant_id"],
            )
        return "INSERT INTO {} (code, parent_code, `name`, `type`, url, remarks, mark_default) VALUES ('{}', '{}', '{}', '{}', '{}', '{}', '{}');".format(
            table_name,
            self.code,
            self.parent_code,
            self.name,
            self._type,
            self._path,
            self.remarks,
            self.default_flag,
        )


class Generate_Permission_SQL_Script(Base_Plugin):
    """生成权限SQL插件"""

    def __init__(self, context) -> None:
        super().__init__()
        self.context = context

    def save_file(self, sql, dir):
        with open(dir, "w", encoding="utf-8") as f:
            f.write(sql)

    def clean_sql(self, table_name, tenant):
        if tenant is not None:
            table_name = "{}{}{}{}{}".format(
                tenant["table_prefix"],
                tenant["delimiter"],
                table_name,
                tenant["delimiter"],
                tenant["tenant_id"],
            )
        return "DELETE FROM {};".format(table_name)

    def run(self, workspace, source):
        _target_path = os.path.join(workspace, "sql")
        if not os.path.exists(_target_path):
            os.makedirs(_target_path)

        workbook = load_workbook(os.path.join(workspace, source))
        _permission = workbook["数据初始化"]

        permission_sql = list()
        permission_tenant_sql = list()
        permission_sql.append(self.clean_sql("hr_permission", None))
        permission_tenant_sql.append(
            self.clean_sql("hr_permission", self.context["init_tenant"])
        )
        permission_code_list = list()
        for row in _permission.rows:
            if (
                row[self.project_config["权限初始化开始列"]].row
                < self.project_config["通用开始行"]
            ):
                continue

            if row[self.project_config["权限初始化开始列"]] is None:
                break

            assert (
                row[self.project_config["权限初始化开始列"]].value
                not in permission_code_list
            ), self.error_log(
                f"""{row[self.project_config["权限初始化开始列"]].value}已存在"""
            )
            permission_code_list.append(
                row[self.project_config["权限初始化开始列"]].value
            )

            permission = Permission(
                row[self.project_config["权限初始化开始列"]].value,
                row[self.project_config["权限初始化开始列"] + 1].value,
                row[self.project_config["权限初始化开始列"] + 2].value,
                row[self.project_config["权限初始化开始列"] + 3].value,
                row[self.project_config["权限初始化开始列"] + 4].value,
                row[self.project_config["权限初始化开始列"] + 5].value,
                row[self.project_config["权限初始化开始列"] + 6].value,
                row[self.project_config["权限初始化开始列"] + 7].value,
            )
            permission_sql.append(permission.sql(None))
            permission_tenant_sql.append(permission.sql(self.context["init_tenant"]))
            self.processed += 1

        permission_sql = "\n".join(permission_sql)
        permission_tenant_sql = "\n".join(permission_tenant_sql)
        self.save_file(
            permission_sql,
            os.path.join(
                _target_path,
                "permission.sql",
            ),
        )
        self.save_file(
            permission_tenant_sql,
            os.path.join(
                _target_path,
                "permission_tenant.sql",
            ),
        )
        del workbook
        gc.collect()
        return source
